package com.dengcj.util;

import java.util.Map;

/**
 * @author dengchunjie
 * @Description: SQL组装工具类
 * @date 2022/1/11 09:47
 */
public class CjSqlUtil {
    /**
     * 组装insert sql
     * @param tablename 表名
     * @param colMap
     * @return
     */
    public static String getInsertSql(String tablename, Map colMap){
        if(colMap == null){
            return "";
        }

        StringBuffer sqlCol = new StringBuffer(),sqlVal = new StringBuffer();
        //然后通过循环遍历出的key值
        colMap.forEach((key,value) -> {
            if(value != null){
                sqlCol.append(","+key);
                sqlVal.append(",'"+value+"'");
            }
        });

        return "insert into " + tablename + "(" + sqlCol.substring(1) + ") values(" + sqlVal.substring(1) + ")";
    }

    /**
     * 组装update sql
     * @param tablename 表名
     * @param colMap
     * @param sqlwhere
     * @return
     */
    public static String getUpdateSql(String tablename,Map colMap,String sqlwhere){
        if(colMap == null || colMap.isEmpty()){
            return "";
        }

        StringBuffer sqlCol = new StringBuffer();
        colMap.forEach((key,value) ->
                sqlCol.append(","+key+"='"+value+"'")
        );

        return "update " + tablename + " set " + sqlCol.substring(1) + " "+sqlwhere;
    }

    /**
     * 组装update sql, 如果值为空则不更新
     * @param tablename 表名
     * @param colMap
     * @param sqlwhere
     * @return
     */
    public static String getUpdateSqlNotNull(String tablename,Map colMap,String sqlwhere){
        if(colMap == null || colMap.isEmpty()){
            return "";
        }

        StringBuffer sqlCol = new StringBuffer();
        colMap.forEach((key,value) ->{
            if(!"".equals(value)) {
                sqlCol.append("," + key + "='" + value + "'");
            }
        });

        return "".equals(sqlCol) ? "" : "update " + tablename + " set " + sqlCol.substring(1) + " "+sqlwhere;
    }
}
